package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.behavior.dto.ReadBehaviorDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApReadBehavior;
import com.heima.behavior.mapper.ApReadBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApReadBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.Threadlocals.UserThreadLocalUtil;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.user.entity.ApUser;
import org.apache.xmlbeans.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP阅读行为表 服务实现类
 * </p>
 *
 * @author 王苑
 * @since 2022-08-04
 */
@Service
public class ApReadBehaviorServiceImpl extends ServiceImpl<ApReadBehaviorMapper, ApReadBehavior> implements IApReadBehaviorService {

    @Autowired
    private IApBehaviorEntryService behaviorEntryService;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Value("${topic.readBehaviorTopic}")
    private String readBehaviorTopic;

    /**
     * 用户阅读行为记录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult read(ReadBehaviorDto dto) {
        //1.获取当前登录用户id， 未登录的获取设备id
        User user = UserThreadLocalUtil.get();
        //封装返回结果
        ApReadBehavior result = null;

        Integer userId = user.getUserId();
        //根据用户id获取用户行为实体对象
//        ApReadBehavior readBehaviorEntity = this.getById(userId);

        dto.setUserId(userId);

        //2.构建用户阅读行为对象
        LambdaUpdateWrapper<ApReadBehavior> updateWrapper = new LambdaUpdateWrapper<>();
        //匹配用户
        updateWrapper.eq(ApReadBehavior::getEntryId, userId);
        //匹配正在查看的文章
        updateWrapper.eq(ApReadBehavior::getArticleId, dto.getArticleId());
        ApReadBehavior readBehavior = this.getOne(updateWrapper);


        if (readBehavior == null) {
            //2.1 查询用户历史阅读记录

            //用户没有阅读过
            ApReadBehavior behavior = new ApReadBehavior();
            //设置属性
            behavior.setCount(1);
            behavior.setEntryId(userId);
            behavior.setArticleId(dto.getArticleId());
            behavior.setReadDuration(dto.getReadDuration());
            behavior.setPercentage(dto.getPercentage());
            behavior.setLoadDuration(dto.getLoadDuration());
            //保存行为对象
            this.save(behavior);

            result = behavior;
        } else {
            //用户阅读过  修改阅读比例、更新阅读时间、增加阅读次数
            //更新阅读比例  TODO 在原有阅读比例基础上增加？
            readBehavior.setReadDuration(dto.getReadDuration());
            //更新阅读时间  当前时间
            readBehavior.setUpdatedTime(new Date());
            //增加阅读次数，在原有基础上
            Integer count = readBehavior.getCount();
            readBehavior.setCount(count + 1);
            this.updateById(readBehavior);
            result = readBehavior;
        }

        //3.发送消息到kafka中
        //3.1 构建发送阅读行为的实体类
        ReadBehaviorDto readBehaviorDto = new ReadBehaviorDto();
        readBehaviorDto.setUserId(userId);
        readBehaviorDto.setArticleId(dto.getArticleId());
        readBehaviorDto.setCount(result.getCount());
        readBehaviorDto.setReadDuration(dto.getReadDuration());
        readBehaviorDto.setPercentage(dto.getPercentage());
        readBehaviorDto.setLoadDuration(dto.getLoadDuration());
        //3.2 发送阅读行为消息到kafka中
        kafkaTemplate.send(readBehaviorTopic, JSON.toJSONString(readBehaviorDto));


    //4.返回结果
        return ResponseResult.okResult(result);
}

    /**
     * 用户阅读行为记录  kafka
     * @param dto
     */
    @Override
    public void saveReadBehavior(ReadBehaviorDto dto) {
        //1.根据用户ID或者设备ID 得到用户行为实体
        ApBehaviorEntry entry = behaviorEntryService.getEntry(dto.getUserId(), dto.getEquipmentId());
        //2.新增 或者 更新用户阅读记录
        LambdaQueryWrapper<ApReadBehavior> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApReadBehavior::getEntryId,entry.getEntryId());
        queryWrapper.eq(ApReadBehavior::getArticleId,dto.getArticleId());
        ApReadBehavior one = this.getOne(queryWrapper);

        ApReadBehavior readBehavior = new ApReadBehavior();
        if (one == null){
            //新增
            readBehavior.setEntryId(entry.getId());
            readBehavior.setCount(dto.getCount());
            readBehavior.setPercentage(dto.getPercentage());
            readBehavior.setReadDuration(dto.getReadDuration());
            readBehavior.setLoadDuration(dto.getLoadDuration());
            readBehavior.setUpdatedTime(new Date());
            this.save(readBehavior);
        }else {
            //已有，则判断
            readBehavior.setCount(dto.getCount()+ 1);
            readBehavior.setPercentage(dto.getPercentage());
            readBehavior.setUpdatedTime(new Date());
            readBehavior.setReadDuration(dto.getReadDuration());
            readBehavior.setLoadDuration(dto.getLoadDuration());
            this.save(readBehavior);
        }

    }
}
